﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyBuildingCMS.BLL.BaseEntity;
using System.Data.Objects.DataClasses;

namespace EasyBuildingCMS.BLL.CoreEngine
{
    public abstract class CoreEngineBaseRepository : BaseRepository
    {
        private CoreEngineEntities _CoreEngineContext;
        private bool disposedValue;

        public CoreEngineBaseRepository()
            : this(Globals.Settings.DefaultConnectionStringName)
        {
            disposedValue = false;        
            CacheKey = "CoreEngine";
        }

        public CoreEngineBaseRepository(string sConnectionString)
        {
            ConnectionString = sConnectionString;
        }

        public override void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected override void Dispose(bool disposing)
        {
            if ((!disposedValue && disposing) && null != _CoreEngineContext)
            {
                _CoreEngineContext.Dispose();
            }
            disposedValue = true;
        }

        public CoreEngineEntities CoreEngineContext
        {
            get
            {
                if (null == _CoreEngineContext)
                {
                    _CoreEngineContext = new CoreEngineEntities(GetActualConnectionString());
                    _CoreEngineContext.ContextOptions.LazyLoadingEnabled = true;
                }
                return _CoreEngineContext;
            }
            set
            {
                _CoreEngineContext = value;
            }
        }

        protected bool SaveChange(int recordID)
        {
            try
            {
                this.CoreEngineContext.SaveChanges();
                BaseRepository.PurgeCacheItems(CacheKey);
                return true;
            }
            catch (Exception ex)
            {
                ActiveExceptions.Add(CacheKey + "_" + recordID, ex);
                return false;
            }
        }
    }
}
